#!/bin/bash

# 招聘系统监控脚本
# 用于监控系统状态、性能指标和日志

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 打印函数
log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

warn() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING: $1${NC}"
}

error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: $1${NC}"
}

info() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')] INFO: $1${NC}"
}

# 检查服务状态
check_services() {
    log "检查服务状态..."
    
    # 检查Docker容器
    echo "Docker容器状态:"
    docker-compose ps
    
    # 检查应用健康状态
    echo -e "\n应用健康检查:"
    if curl -f -s http://localhost:8080/api/health > /dev/null; then
        echo -e "${GREEN}✓ 后端服务: 正常${NC}"
    else
        echo -e "${RED}✗ 后端服务: 异常${NC}"
    fi
    
    if curl -f -s http://localhost > /dev/null; then
        echo -e "${GREEN}✓ 前端服务: 正常${NC}"
    else
        echo -e "${RED}✗ 前端服务: 异常${NC}"
    fi
    
    # 检查数据库连接
    echo -e "\n数据库连接检查:"
    if docker exec employment-mysql mysqladmin ping -h localhost -u root -proot123456 &> /dev/null; then
        echo -e "${GREEN}✓ MySQL: 连接正常${NC}"
    else
        echo -e "${RED}✗ MySQL: 连接异常${NC}"
    fi
    
    # 检查Redis连接
    if docker exec employment-redis redis-cli ping &> /dev/null; then
        echo -e "${GREEN}✓ Redis: 连接正常${NC}"
    else
        echo -e "${RED}✗ Redis: 连接异常${NC}"
    fi
}

# 检查系统资源
check_resources() {
    log "检查系统资源使用情况..."
    
    # CPU使用率
    echo "CPU使用率:"
    top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}'
    
    # 内存使用率
    echo -e "\n内存使用情况:"
    free -h
    
    # 磁盘使用率
    echo -e "\n磁盘使用情况:"
    df -h
    
    # Docker容器资源使用
    echo -e "\nDocker容器资源使用:"
    docker stats --no-stream
}

# 查看日志
check_logs() {
    local service=$1
    local lines=${2:-50}
    
    log "查看 $service 服务日志 (最近 $lines 行)..."
    
    case $service in
        backend|app)
            docker-compose logs --tail=$lines employment-backend
            ;;
        mysql|db)
            docker-compose logs --tail=$lines employment-mysql
            ;;
        redis)
            docker-compose logs --tail=$lines employment-redis
            ;;
        nginx)
            docker-compose logs --tail=$lines employment-nginx
            ;;
        all)
            docker-compose logs --tail=$lines
            ;;
        *)
            error "未知的服务: $service"
            error "可用服务: backend, mysql, redis, nginx, all"
            exit 1
            ;;
    esac
}

# 备份数据库
backup_database() {
    log "开始备份数据库..."
    
    BACKUP_DIR="./backups"
    BACKUP_DATE=$(date +%Y%m%d_%H%M%S)
    BACKUP_FILE="$BACKUP_DIR/employment_db_backup_$BACKUP_DATE.sql"
    
    # 创建备份目录
    mkdir -p $BACKUP_DIR
    
    # 执行备份
    docker exec employment-mysql mysqldump -u root -proot123456 employment_db > $BACKUP_FILE
    
    if [ $? -eq 0 ]; then
        log "数据库备份成功: $BACKUP_FILE"
        
        # 压缩备份文件
        gzip $BACKUP_FILE
        log "备份文件已压缩: $BACKUP_FILE.gz"
        
        # 清理7天前的备份
        find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete
        log "已清理7天前的备份文件"
    else
        error "数据库备份失败"
        exit 1
    fi
}

# 重启服务
restart_service() {
    local service=$1
    
    log "重启 $service 服务..."
    
    case $service in
        backend|app)
            docker-compose restart employment-backend
            ;;
        mysql|db)
            docker-compose restart employment-mysql
            ;;
        redis)
            docker-compose restart employment-redis
            ;;
        nginx)
            docker-compose restart employment-nginx
            ;;
        all)
            docker-compose restart
            ;;
        *)
            error "未知的服务: $service"
            exit 1
            ;;
    esac
    
    log "$service 服务重启完成"
}

# 清理日志
clean_logs() {
    log "清理日志文件..."
    
    # 清理应用日志
    find ./logs -name "*.log" -mtime +30 -delete
    
    # 清理Docker日志
    docker system prune -f
    
    log "日志清理完成"
}

# 性能测试
performance_test() {
    log "开始性能测试..."
    
    # 使用curl进行简单的性能测试
    echo "API响应时间测试:"
    
    for i in {1..10}; do
        response_time=$(curl -o /dev/null -s -w '%{time_total}' http://localhost:8080/api/health)
        echo "请求 $i: ${response_time}s"
    done
    
    log "性能测试完成"
}

# 显示帮助信息
show_help() {
    echo "招聘系统监控脚本"
    echo
    echo "使用方法: $0 <command> [options]"
    echo
    echo "命令:"
    echo "  status              检查服务状态"
    echo "  resources           检查系统资源"
    echo "  logs <service>      查看服务日志"
    echo "  backup              备份数据库"
    echo "  restart <service>   重启服务"
    echo "  clean               清理日志"
    echo "  performance         性能测试"
    echo "  help                显示此帮助信息"
    echo
    echo "服务选项:"
    echo "  backend, mysql, redis, nginx, all"
    echo
    echo "示例:"
    echo "  $0 status"
    echo "  $0 logs backend"
    echo "  $0 restart all"
}

# 主逻辑
case $1 in
    status)
        check_services
        ;;
    resources)
        check_resources
        ;;
    logs)
        check_logs $2 $3
        ;;
    backup)
        backup_database
        ;;
    restart)
        restart_service $2
        ;;
    clean)
        clean_logs
        ;;
    performance)
        performance_test
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        error "未知命令: $1"
        show_help
        exit 1
        ;;
esac